<template>
    <div class="article-manage-container">
        <!-- 文章搜索栏 -->
        <el-form :inline="true" :model="searchForm" class="search-form" label-width="80px">
            <el-form-item label="文章标题">
                <el-input v-model="searchForm.searchTitle" placeholder="请输入标题关键词" clearable
                    style="width: 300px;"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="getArticleList(1)">搜索</el-button>
                <el-button type="primary" @click="toAddArticle">添加文章</el-button>
            </el-form-item>
        </el-form>

        <!-- 文章列表 -->
        <el-table v-loading="listLoading" :data="articleList" border stripe style="width: 100%; margin-top: 15px;">
            <el-table-column prop="title" label="文章标题" min-width="100"></el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="200" align="center"></el-table-column>
            <el-table-column label="预览图"><template slot-scope="scope">
                    <img :src="scope.row.titleImage" style="width: 50px; height: 50px;">
                </template></el-table-column>
            <el-table-column label="操作" width="180" align="center">
                <template slot-scope="scope">
                    <el-button type="text" size="small" @click="openEditModal(scope.row.id)">编辑</el-button>
                    <el-button type="text" size="small" color="#f56c6c"
                        @click="handleDelete(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页控件 -->
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="pageParams.current" :page-sizes="[10, 20, 30]" :page-size="pageParams.size"
            layout="total, sizes, prev, pager, next, jumper" :total="this.totalCount"
            style="margin-top: 20px; text-align: right;"></el-pagination>

        <!-- 编辑文章模态框 -->
        <el-dialog title="编辑文章" :visible.sync="editModalVisible" width="70%" :before-close="closeEditModal">
            <el-loading name="aaaa" v-if="editLoading" text="加载文章详情中..." fullscreen></el-loading>
            <el-form v-else :model="editForm" label-width="100px" class="edit-form">
                <el-form-item label="文章标题" required>
                    <el-input v-model="editForm.title" placeholder="请输入文章标题" style="width: 80%;"></el-input>
                </el-form-item>
                <el-form-item label="文章内容" required>
                    <el-input v-model="editForm.content" type="textarea" rows="8" placeholder="请输入文章内容"
                        style="width: 80%;"></el-input>
                </el-form-item>
                <el-form-item label="封面">
                    <img :src="editForm.titleImage" alt="" style="width: 50px;height: 50px;">
                </el-form-item>
                <el-form-item label="摘要" required>
                    <el-input v-model="editForm.description" placeholder="请输入摘要内容" style="width: 80%;"></el-input>
                </el-form-item>
                <el-form-item label="分类" required>
                    <el-input v-model="editForm.categoryId" placeholder="请输入分类" style="width: 80%;"></el-input>
                </el-form-item>
                <el-form-item label="标签" required>
                    <el-input v-model="editForm.tagIds" placeholder="请添加标签" style="width: 80%;"></el-input>
                </el-form-item>

            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editModalVisible = false">取消</el-button>
                <el-button type="primary" @click="submitEdit">保存修改</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    name: 'ArticleManage',
    data() {
        return {
            // 列表相关
            articleList: [], // 文章列表数据
            listLoading: false, // 列表加载状态
            totalCount: 0, // 文章总条数
            pageParams: { current: 1, size: 10 }, // 分页信息，统一命名为pageParams
            searchForm: { searchTitle: '' }, // 搜索表单

            // 编辑模态框相关
            editModalVisible: false, // 模态框显示状态
            editLoading: false, // 编辑加载状态
            editForm: { id: '', title: '', content: '' } // 编辑表单数据
        }
    },
    mounted() {
        this.getArticleList(); // 页面加载时获取文章列表
    },
    methods: {
        //跳转添加页面
        toAddArticle() {
            this.$router.push('/add')
        },
        //  获取文章列表
        async getArticleList() {
            this.listLoading = true;
            try {
                const res = await this.$axios.post(
                    '/api/admin/article/list',
                    {
                        ...this.pageParams,
                        searchTitle: this.searchForm.searchTitle // 合并分页参数和搜索参数
                    }
                );
                if (res.data.success) {
                    console.log(res);
                    this.articleList = res.data.data.records;
                    this.totalCount = res.data.data.total;
                    console.log(this.articleList);


                } else {
                    this.$message.error(`获取列表失败：${res.data.message || '未知错误'}`);
                }
            } catch (err) {
                this.$message.error('接口请求异常，请稍后重试');
                console.error('ArticleList request error:', err);
            } finally {
                this.listLoading = false;
            }
        },

        //  打开编辑模态框（获取文章详情）
        async openEditModal(articleId) {
            console.log(articleId);

            try {
                this.editLoading = true;
                this.editModalVisible = true;
                const res = await this.$axios.post('/api/admin/article/detail', { articleId });
                if (res.data.success) {
                    this.editForm = res.data.data;
                    console.log(this.editForm);

                } else {
                    this.$message.error(res.data.message || '获取文章详情失败');
                    this.editModalVisible = false;
                }
            } catch (err) {
                console.error('获取文章详情失败：', err);
                this.editModalVisible = false;
            } finally {
                this.editLoading = false;
            }
        },

        closeEditModal() {
            this.editModalVisible = false;
            this.editForm = { id: '', title: '', content: '' };
        },

        async submitEdit() {
            try {
                await this.$axios.post('/api/admin/article/update', this.editForm);
                this.$message.success('文章修改成功');
                this.closeEditModal();
                this.getArticleList(); // 刷新列表
            } catch (err) {
                console.error('提交文章修改失败：', err);
                this.$message.error('修改失败，请重试');
            }
        },

        async handleDelete(articleId) {
            console.log(articleId);

            try {
                await this.$confirm('确定要删除这篇文章吗？删除后不可恢复！', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                });

                await this.$axios.post('/api/admin/article/delete', { articleId });
                this.$message.success('文章删除成功');
                this.getArticleList(); // 刷新列表
            } catch (err) {
                console.error('删除文章失败：', err);
                this.$message.info('已取消删除');
            }
        },

        handleSizeChange(val) {
            this.pageParams.size = val;
            this.pageParams.current = 1; // 重置为第一页
            this.getArticleList();
        },
        handleCurrentChange(val) {
            this.pageParams.current = val;
            this.getArticleList();
        }
    }
}
</script>

<style scoped>
.article-manage-container {
    padding: 20px;
}

.search-form {
    margin-bottom: 10px;
}

.edit-form {
    padding: 10px 0;
}
</style>